<template>
  <transition>
    <div class="report-order-details">

      <section class="app-main">
        <div class="main-content">
          <div class="order-state" v-if="res.cancelFlag=='1' && res.bookStatus!=3905">申请取消中</div>
          <template v-else>
            <div class="order-state" v-if="res.bookStatus==3900">预约中</div>
            <div class="order-state" v-if="res.bookStatus==3901">已确认</div>
            <div class="order-state" v-if="res.bookStatus==3902">已派工</div>
            <div class="order-state" v-if="res.bookStatus==3903">维修中</div>
            <div class="order-state" v-if="res.bookStatus==3904">已完成</div>
            <div class="order-state" v-if="res.bookStatus==3905">已取消</div>
            <!--<div class="order-state" v-else>{{res.bookStatusDesc}}</div>-->
            <mt-button v-if="res.bookStatus==3900 ||res.bookStatus==3901 || res.bookStatus==3902 || res.bookStatus==3903" type="primary" class="main-content-button" @click.native="popupAddPic=true">补充图片/需求信息</mt-button>

          </template>
        </div>
        <div class="module-product">
        <div class="product-content" v-for="item in res.items" v-if="item.itemType==3801" @click="handleGoDetails(item.commattribId)">
          <div class="product-img">
            <!--<mt-swipe :auto="4000" class="pic-car">-->
              <!--<mt-swipe-item v-for="item in picList">-->
                <!--<img :src="item.src" @click="handleCheckPic">-->
              <!--</mt-swipe-item>-->
            <!--</mt-swipe>-->
            <img :src="noneImg"/>
          </div>
          <ul class="product-details">
            <li class="item item-title">{{item.commattribName}}</li>
            <li class="item item-count">数量：{{item.qty}}</li>
            <li class="item item-price">
              ￥<span class="price">{{item.price}}</span>
              <!--<span class="item-factory">品牌件</span>-->
            </li>
          </ul>
        </div>
          <a class="action-phone" href="tel:400-968-3360"><span class="iconfont icon-kefuzhuanhuan" style="margin-right: 4px;"></span>联系客服</a>
        </div>
        <div class="word-car-img" v-if="files.length>0">
          <div class="car-img-title">预约车辆图</div>
          <ul class="car-repair-list">
            <li class="car-repair-item" v-for="(item,index) in files" @click="handleCheckPic('0')">
              <img class="img" :src="item.src"/>
            </li>
          </ul>
        </div>
        <div class="module-block">
          <mt-cell
            title="单号:" class="mint-field">
            {{res.sn}}
          </mt-cell>
          <mt-cell
            title="预约时间:" class="mint-field">
            <template v-if="res.bookTimeStart">{{(res.bookTimeStart).split(' ')[0]}} {{new Date(res.bookTimeStart).getHours()}}:00~{{new Date(res.bookTimeEnd).getHours()}}:00</template>
          </mt-cell>
          <mt-cell
            title="服务方式:" class="mint-field">
            <span v-if="res.serviceType==4101">上门安装</span>
            <span v-if="res.serviceType==4102">到店安装</span>
          </mt-cell>
          <template v-if="res.serviceType==4101">
          <mt-cell
            title="联系电话:" class="mint-field">
            {{res.linkPhone}}
          </mt-cell>
          <mt-cell
            title="联系地址:" class="mint-field">

            {{res.linkAddress}}
          </mt-cell>
          </template>

          <mt-cell
            title="车型:" class="mint-field">
            {{res.carModel}}
          </mt-cell>
          <mt-cell
            title="备注:" class="mint-field">
            {{res.remark}}
          </mt-cell>

          <mt-cell
            title="提交时间:" class="mint-field">
            {{res.createTime}}
          </mt-cell>
        </div>
        <div class="word-car-img" v-if="picRepair.length>0">
          <div class="car-img-title">完工图</div>
          <ul class="car-repair-list">
            <li class="car-repair-item" v-for="(item,index) in picRepair" @click="handleCheckPic('1')">
              <img class="img" :src="item.src"/>
            </li>
          </ul>
        </div>
        <dl class="module-block">
          <dd class="word-content" v-for="item in res.items" v-if="item.itemType==3802">
            <div>{{item.serviceName}}:<span class="text-red pull-right">￥{{item.amount}}</span></div>
          </dd>
          <dd class="word-content" v-if="getProductPrice!=0">
            <div>商品总额:<span class="text-red pull-right">￥{{getProductPrice}}</span></div>
          </dd>
          <dd class="word-content">实付总额:<span class="text-red pull-right">￥{{res.amount}}</span></dd>
        </dl>
        <div class="button-content-bottom" v-if="res.cancelFlag!='1'">
          <mt-button v-if="res.bookStatus==3900 || res.bookStatus==3901 || res.bookStatus==3902 || res.bookStatus==3903" type="default" @click.native="handleCloseOrder">取消订单</mt-button>
          <mt-button v-if="res.bookStatus==3901 && res.payType==4901" type="primary" @click.native="handleToPayWX">立即支付</mt-button>
          <mt-button v-if="res.bookStatus==3904" type="primary" @click.native="handleActionProduct">再次报修</mt-button>
        </div>
        <!--图片大图弹窗-->
        <mt-popup
          v-model="popupSwiper"
          position="middle" class="me-popup-pic">
          <popup-swiper v-bind:picList="needPicList" @popupSwiperClose="popupSwiper=false"></popup-swiper>
        </mt-popup>
        <!--图片大图弹窗-->

        <mt-popup
          v-model="popupAddPic"
          position="bottom" class="popup-add-pic" v-if="popupAddPic==true">
          <div class="module-commnents">
            <!--{{myUploads}}-->
            <div class="comments-title">备注信息</div>
            <textarea v-model="comments" class="item-textarea" placeholder="给派派捎句话" oninput="this.style.height=this.scrollHeight + 'px'"></textarea>
          </div>
          <div class="module-add-img">
            <div class="block-header">*建议提供车架号、整车图、破损部位等图片。</div>
            <uploadOssImg v-bind:showPopupImg="'false'" v-bind:oldFiles="files" v-bind:myFileLocate="''" @myMediaAttr="getMyMediaAttr" @getAccessToken="getAccessToken"></uploadOssImg>
          </div>
          <div class="button-content">
            <div class="button-block-6">
              <mt-button type="danger" @click="popupAddPic = false">关闭</mt-button>
            </div>
            <div class="button-block-6">
              <mt-button type="primary" @click.native="handleAddInfo">确认提交</mt-button>
            </div>
          </div>
        </mt-popup>
        <!--地图弹窗-->

        <!--管理员申请取消弹窗-->
        <mt-popup
          v-model="popupApplyCancel"
          position="bottom" class="popup-apply-cancel">
          <div class="module-store-info">
            <span class="module-title">取消原因</span>
            <div class="module-content">
              <textarea v-model="cancelApplyReason" class="item-textarea" placeholder="请输入取消原因" oninput="this.style.height=this.scrollHeight + 'px'"></textarea>
            </div>
          </div>
          <div class="button-content">
            <div class="button-block-6">
              <mt-button type="danger" @click="popupApplyCancel = false">关闭</mt-button>
            </div>
            <div class="button-block-6">
              <mt-button type="primary" @click="handleSureApplyCancel">提交</mt-button>
            </div>
          </div>
        </mt-popup>
        <!--管理员申请取消弹窗-->
      </section>
    </div>
  </transition>
</template>

<script>
  import { Navbar,Button,MessageBox,Toast ,Checklist,Cell,DatetimePicker,Indicator} from 'mint-ui';
  import popupSwiper from '../common/popup-swiper';
  import uploadOssImg from '../common/upload-oss-img.vue'
  import wechatAuthorize from '../../common/wechat-authorize'
  export default {
    components:{
      popupSwiper,
      uploadOssImg,
    },
    data () {
      return {
        popupAddPic:false,
        popupApplyCancel:false,
        cancelApplyReason:'',
        comments:'',
        res:'',
        needPicList:[],
        popupSwiper:false,
        noneImg:'./static/img/img-none.jpg',
        accessToken:'',
        files:[],
        picRepair:[],
        mediaAttr:[],
        uploads:[],
        myUploads:[],
      }
    },

    /**进入页面判断手机环境**/
    beforeRouteEnter (to, from, next) {
      var u = navigator.userAgent;
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      // XXX: 修复iOS版微信HTML5 History兼容性问题
      if (isiOS && to.path !== location.pathname) {
        // 此处不可使用location.replace
        location.assign(to.fullPath)
      } else {
        next()
      }
    },
    mounted(){

      /**加载详情和图片**/
      this.getData();
      this.getImg();
    },
    computed:{
      /**计算产品总价**/
      getProductPrice:function(){
        if(this.res.items){
          let total=0;
          for(var i=0;i<this.res.items.length;i++){
            if(this.res.items[i].itemType==3801){
              total+=(this.res.items[i].price)*(this.res.items[i].qty)
            }
          }
          return total;
        }
      }
    },
    methods:{
      /**加载图片**/
      getImg(){
        this.files=[];
        this.picRepair=[];
        this.mediaAttr=[];
        this.myUploads=[];
        var params = new URLSearchParams();
        params.append('form.bookId', this.$route.query.id);
        this.$axios({
          method: 'post',
          url:'gp/app/bookingOrderApp!getUploads.do',
          data:params,
        }).then((res)=>{
          console.log(res)
        if(res.data.result==true && res.data.statusCode==200){
          this.uploads=res.data.object;
          for(var i=0;i<this.uploads.length;i++){
            var item = {
              uploadId:this.uploads[i].uploadId,
              name: this.uploads[i].sourceFileName,
              tag : this.uploads[i].etag,
              fileLocate:this.uploads[i].fileLocate,
              src: 'https://rmcbapp.oss-cn-shenzhen.aliyuncs.com/'+this.uploads[i].ossPath+'?x-oss-process=image/resize,m_fixed,w_500',
            }
            if(this.uploads[i].fileType==1){
              this.picRepair.push(item);
            }else if(this.uploads[i].fileType==0){
              item.tag='1'
              this.files.push(item);
            }
            this.mediaAttr.push(item);
            this.myUploads.push(item);
          }

        }else{
          Toast({
            message: res.data.message,
            position: 'middle',
            duration:1200
          });
        }
      });
      },
      /**加载详情**/
      getData(){
        var params = new URLSearchParams();
        params.append('form.bookId', this.$route.query.id);
        this.$axios({
          method: 'post',
          url:'gp/bu/bookingOrderApp!ajaxBookingOrder.do',
          data:params,
        }).then((res)=>{
          console.log(res)
          if(res.data.result==true && res.data.statusCode==200){
            this.res=res.data.object;
            this.comments=this.res.remark
          }else{
            Toast({
              message: res.data.message,
              position: 'middle',
              duration:1200
            });
          }
        });
      },

      /**获取accessToken**/
      getAccessToken(data){
        this.accessToken=data;
      },

      /**获取车辆维修图**/
      getMyMediaAttr(data){
        this.mediaAttr=data
      },

      /**查看产品详情**/
      handleGoDetails(id){
        this.$router.push({path:'/product-details',query: {id:id}})
      },

      /**查看大图**/
      handleCheckPic(type){
        if(type=='0'){
          this.needPicList=this.files;

        }else if(type=='1'){
          this.needPicList=this.picRepair;
        }
        this.popupSwiper=true;
      },

      /**再次报修**/
      handleActionProduct(){
        this.$router.push({path:'/app-carmodel-search'})
      },

      /**提交取消原因**/
      handleSureApplyCancel(){
          if(this.cancelApplyReason==''){
            Toast({
              message: '请输入取消原因',
              position: 'middle',
              duration:800
            });
            return false;
          }
          Indicator.open({
            text: '申请提交中...',
            spinnerType: 'snake'
          });
          var params = new URLSearchParams();
          const postData={
            id:this.$route.query.id,
            cancelReason:this.cancelApplyReason
          };
          params.append('requestData',JSON.stringify(postData));
          this.$axios({
            method: 'post',
            url:'gp/bu/bookingOrderApp!cancelApply.do',
            data:params
          }).then((res)=>{
            console.log(res)
          if(res.data.result==true){
            Indicator.close();
            Toast({
              message: res.data.message,
              position: 'middle',
              duration:800
            });
            this.popupApplyCancel=false;
            this.getData();
          }else{
            Indicator.close();
            Toast({
              message: res.data.message,
              position: 'middle',
              duration:1000
            });
            this.popupApplyCancel=false;
          }
        })
      },

      handleCloseOrder(){
        this.popupApplyCancel=true;
      },
      /**获取oss配置**/
      getOss(){
        let OSS = require('ali-oss');
        this.client = new OSS({
          region: "oss-cn-shenzhen",
          secure: true,//https
          endpoint: 'oss-cn-shenzhen.aliyuncs.com',
          accessKeyId: "LTAIPCNdQvX5yOwc",
          accessKeySecret: "7bReGAz8bc9aJdK4IAz5KW5fnNOzrQ ",
          bucket: 'rmcbapp'
        });
      },

      /**toBuffer**/
      toBuffer(ab) {
        var buf = new Buffer(ab.byteLength);
        var view = new Uint8Array(ab);
        for (var i = 0; i < buf.length; ++i) {
          buf[i] = view[i];
        }
        return buf;
      },

      /**提交修改信息**/
      handleAddInfo(){
        this.getOss();
        var that=this;
        that.bookingApi();
        console.log(that.mediaAttr,111)
        if(that.mediaAttr.length>0){
          for(var i=0;i<that.mediaAttr.length;i++){
            const mediaId = that.mediaAttr[i].serverId; // 微信多媒体文件id
            const tag = that.mediaAttr[i].tag; // 微信多媒体文件id
            if(tag==''){
                Indicator.open({
                  text: '补充信息提交中...',
                  spinnerType: 'snake'
                });

                /**通过mediaId从微信获取图片流**/
                that.$axios({
                  method: 'get',
                  url:'wx/cgi-bin/media/get?access_token='+that.accessToken+'&media_id='+mediaId,
                  responseType:'arraybuffer',
                }).then((res)=>{

                  /**arrayBuffer转Buffer**/
                  var buffer = that.toBuffer(res.data);
                  var destPath = 'erpDemand/'+mediaId+'.jpg'; // OSS文件路径
                  var postitem={}
                  /**上传到阿里云**/
                  that.client.put(destPath, buffer).then((result) => {
                    console.log('图片上传阿里云结果', result);
                    var item='https://rmcbapp.oss-cn-shenzhen.aliyuncs.com/'+result.name;

                    postitem={
                      bucketName:'rmcbapp',
                      fileType:0,
                      sourceFileName:mediaId+'.jpg',
                      ossPath:result.name,
                      ossKey:'rmcbapp/'+result.name,
                      etag:result.res.headers.etag
                    }
                    that.myUploads.push(postitem);
                    if(that.myUploads.length==i){
                      that.bookingApi();
                    }
                    }).catch((err) => {
                        console.log(err)
                      Toast({
                        message: '图片上传失败',
                        position: 'middle',
                        duration:1000
                      });
                    });
                  })
              }else{
                console.log('该图片已上传')
              }
          };
        }
      },
      /**和后台交互接口**/
      bookingApi(){
        var that=this;
        var params = new URLSearchParams();
        const postData={
          shopId:'1000001',
          demandType:'4601',
          bookId:that.$route.query.id,
          uploads:that.myUploads,
          remark:that.comments,
        }
        params.append('demandData',JSON.stringify(postData));
        that.$axios({
          method: 'post',
          url:'gp/app/bookingOrderApp!saveBooking.do',
          data:params
        }).then((res)=>{
          if(res.data.result==true){
          Toast({
            message: '提交成功',
            position: 'middle',
            duration:1200
          });
          setTimeout(()=>{
            window.location.reload();
          },1100)
        }else{
          Toast({
            message: res.data.message,
            position: 'middle',
            duration:1000
          });
        }
      });
      },
      /**弹窗支付**/
      handleToPayWX(){
        wechatAuthorize.handleToPayWX(this.$route.query.id,this.res.sn,this.res.amount,'预约单支付',0);
      },
    }
  }
</script>

<style>

  .report-order-details{
    overflow: hidden;
  }
  .report-order-details .app-main{
    padding:0 0 52px;
  }
  .report-order-details .module-store-info .module-content{
    padding:12px 12px;
  }
  .report-order-details .item-textarea{
    height:100px;
    min-height:100px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border-radius: 0;
    border: 0;
    outline: 0;
    padding:6px 10px;
    font-size: 15px;
    width: 100%;
    box-shadow: 1px 1px 6px 2px rgba(0,0,0,0.08) inset;
  }
  .report-order-details .module-title{
    background-color:#f5f5f5;
    display: block;
    padding:18px 12px 12px;
    font-size:16px;
  }
  .report-order-details .module-title:before{
    background:#c34853;
    position: relative;
    top:-2px;
    display:inline-block;
    vertical-align: middle;
    width:2px;
    height:16px;
    content: '';
    margin-right:4px;
  }

  .report-order-details .popup-apply-cancel{
    width: 100%;
  }
  .report-order-details .main-content{
    background: -webkit-linear-gradient(right, #03adf3 , #0080e5); /* Safari 5.1 - 6.0 */
    background: -o-linear-gradient(left, #03adf3 , #0080e5); /* Opera 11.1 - 12.0 */
    background: -moz-linear-gradient(left, #03adf3 , #0080e5); /* Firefox 3.6 - 15 */
    background: linear-gradient(to left, #03adf3 , #0080e5); /* 标准的语法 */
    color: #fff;
    text-align: center;
    padding: 40px 0;
  }
  .report-order-details .main-content .order-state{
    font-size: 22px;
    font-weight:400;
    margin:0 0 6px;
    letter-spacing:1px;
  }
  .report-order-details .main-content-button{
    background: #fff;
    color: #26a2ff;
    font-size: 14px;
    height: 32px;
    border-radius: 15px;
  }
  .report-order-details .mint-field .mint-cell-title{
    width: 80px;
  }
  .report-order-details .mint-field .mint-cell-wrapper{
    border-bottom:1px solid #eee;
    background:none;
    padding:10px;
    font-size: 15px;
    color: #666;
  }
  .report-order-details .mint-field .mint-cell-value{
    text-align: right;
  }
  .report-order-details .mint-field .mint-field-core{
    padding-left: 16px;
  }
  .report-order-details .module-product{
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    position: relative;
    top: -12px;
  }
  .report-order-details .product-content{
    padding: 12px 12px 0;
    font-size:14px;
  }
  .report-order-details .product-content .product-img{
    display: table-cell;
    vertical-align: top;
    padding-right: 12px;
    width: 32%;
  }
  .report-order-details .product-content .product-img img{
    width: 100px;
    height: 100px;
  }
  .report-order-details .product-content .product-details{
    position: relative;
    display: table-cell;
    vertical-align: top;
    width: 68%;
  }
  .report-order-details .product-content .item{
    margin:0 0 4px;
  }
  .report-order-details .product-content .item-title{
    font-size: 15px;
    color: #000;
    margin:0 0 6px;
    line-height: 22px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp:2;
    overflow: hidden;

  }
  .report-order-details .product-content .item-count{
    font-size: 13px;
    color: #888;
  }

  .report-order-details .product-content .item-price{
    padding:12px 0 0;
    color: red;
    font-size: 16px;
  }
  .report-order-details .product-content .item-img{
    margin:0 0 10px;
  }

  .report-order-details .module-block{
    background: #fff;
    margin:0 0 12px;
    border-radius: 12px;
    overflow: hidden;
  }
  .report-order-details .word-content{
    background: #fff;
    padding:14px 12px;
    font-size: 15px;
    color:#666;
    margin: 0;
    line-height: 20px;
    border-top:1px solid #f5f5f5;
  }

  .report-order-details .button-content{
    padding:16px 16px ;
    font-size:0;
  }
  .report-order-details .button-content .mint-button{
    width: 100%;
    font-size: 16px;
  }
  .report-order-details .button-block-6{
    display: inline-block;
    width: 50%;
    padding:0 8px;
  }
  .report-order-details .block-header{
    position: relative;
    display: block;
    top: 3px;
    padding:12px 6px 0;
    font-size:14px;
    color: #666;
  }
  .report-order-details .pic-car .mint-swipe-items-wrap{
    height: 100px;
  }
  .report-order-details .pic-car .mint-swipe-indicators{
    display: none;
  }

  .report-order-details .me-popup-pic{
    width: 100%;
    height:100%;
  }
  .report-order-details .me-popup-pic .mint-swipe,.report-order-details .me-popup-pic .mint-swipe-items-wrap{
    height: 100% !important;
  }
  .report-order-details .button-content-bottom{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;
    display: flex;
    height: 54px;
    padding:0 16px;
    justify-content:flex-end;
    align-items: center;
    box-shadow: 0px -6px 4px 0px rgba(0, 0, 0, 0.03);
  }
  .report-order-details .button-content-bottom .mint-button{
    justify-content: center;
    font-size: 14px;
    box-shadow: none;
    height: 34px;
    margin-left: 12px;

  }
  .report-order-details .action-phone{
    display: block;
    margin: 16px 0 0;
    padding:12px 0;
    border-top:1px solid #eee;
    text-align: center;

  }
  .report-order-details .word-car-img{
    background:#fff;
    margin: 0 0 12px;
  }
  .report-order-details .word-car-img .car-repair-list{
    display: flex;
    margin:0 -6px;
    overflow: auto;
    padding: 0 0 12px;
  }
  .report-order-details .word-car-img .car-repair-item{
    display: flex;
    flex:1;
    width:27%;
    min-width:27%;
    max-width:27%;
    padding:0 6px;
  }
  .report-order-details .word-car-img .car-repair-item img{
    width:100%;
    height:80px;
  }
  .report-order-details .word-car-img .car-img-title{
    padding:8px;
    font-size: 13px;
    color: #666;
  }
  .report-order-details .popup-add-pic{
    width: 100%;
    height:80%;
    padding:12px;
    overflow: auto;
  }
  .report-order-details .popup-add-pic .comments-title{
    font-size: 13px;
    color: #666;
    padding:4px 6px 10px;
  }
</style>
